package cn.itcast.mybatis.demo4;

import static org.junit.Assert.*;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import cn.itcast.mybatis.pojo.User;

public class UserMapperTestCase {

	
	/**
	 * 实现对user表的增删改查
	 */
	private SqlSession sqlSession;
	
	
	@Before
	public  void init() throws IOException{
		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
		//使用build方法出入mybatis的核心配置文件，然后才可以创建sqlSessionFactory
		//获取sqlSessionFactory
		SqlSessionFactory build = builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
		//获取sqlSession
		sqlSession= build.openSession();
	}
	
	/**
	 * 通过id来进行查询
	 */
	@Test
	public void getUserById() {
		//使用jdk的动态代理来获取UserMapper接口的代理对象
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		User userById = mapper.getUserById(16);
		System.out.println(userById.toString());
		sqlSession.close();
	}
	
	/**
	 * 通过地址来进行模糊查询
	 * @throws Exception
	 */
	@Test
	public void getUserByAddress() throws Exception {
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		List<User> userList = mapper.getUserByAddress("河南");
		for (User user : userList) {
			System.out.println(user.toString());
		}
		sqlSession.close();
	}
	
	/**
	 * 添加用户
	 * @throws Exception
	 */
	@Test
	public void insertUser() throws Exception {
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		User user = new User();
		user.setAddress("广西");
		user.setBirthday(new Date());
		user.setSex("0");
		user.setUsername("洪秀全");
		mapper.insertUser(user);
		sqlSession.commit();
		sqlSession.close();
	}
	
	
	
	@Test
	public void updateUser() throws Exception {
		UserMapper mapper = sqlSession.getMapper(UserMapper.class);
		User user = new User();
		user.setId(30);
		user.setUsername("张三");
		mapper.updateUser(user);
		sqlSession.commit();
		sqlSession.close();
	}
	
	
	
	
	
	

}
